//
//  AsyncGETParser.m
//  SmileRead
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "AsyncGETParser.h"
#import "Reachability.h"
#import "Path.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"

@interface AsyncGETParser () <NSURLConnectionDataDelegate, NSURLConnectionDelegate>

@property (nonatomic, retain) NSMutableData *reData;

@property (nonatomic, retain) NSString *fileName;

@property (nonatomic, retain) MBProgressHUD *mb;

@end


@implementation AsyncGETParser

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.reData = [NSMutableData data];
    }
    return self;
}

- (void)dealloc
{
    [_fileName release];
    [_reData release];
    Block_release(_Myblock);
    [super dealloc];
}

+ asyncGETParserWithURLString:(NSString *)Urlstr fileName:(NSString *)fileName pamarters:(NSDictionary *)pamaters block:(void(^)(NSData *data))block

{
    // 拼接网址
    NSArray *keys = [pamaters allKeys];
    NSArray *values = [pamaters allValues];
    NSMutableString *string = [NSMutableString string];
    for (int i = 0; i < keys.count; i++) {
        if (i < keys.count) {
            [string appendFormat:@"&%@=%@",keys[i], values[i]];
        }
        else {
            [string appendFormat:@"%@=%@", keys[i], values[i]];
        }
    }
    NSString *URLString = [NSString stringWithFormat:@"%@%@", Urlstr, string];
    
    URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AsyncGETParser *parser = [[AsyncGETParser alloc] init];
    parser.Myblock = block;
    // 文件夹名
    parser.fileName = fileName;
    
    // 创建第三方类
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    // 判断网络的链接
    
    // 有网的状态
    if ([reach isReachable]) {
        [parser startWithURLString:URLString];
    }
    // 无网的状态
    else {
        
        NSLog(@"无网的状态");
        
        // 判断文件是否存在
        NSString *path = [Path pathOfLibraryWithFileName:fileName];
        NSFileManager *file = [NSFileManager defaultManager];
        // 有缓存
        if ([file fileExistsAtPath:path] == YES) {
            // 从文件中读取数据
            NSData *data = [NSData dataWithContentsOfFile:path];
            parser.Myblock(data);
        }
        
#warning 无网无数据的处理还没完成
        // 无网无数据
        else {
            NSLog(@"无网无数据");
        }
    }
    return [parser autorelease];
}

- (void)startWithURLString:(NSString *)Urlstr
{
    AppDelegate *tempAppDelegate = [[UIApplication sharedApplication] delegate];
    self.mb = [MBProgressHUD showHUDAddedTo:tempAppDelegate.window animated:YES];
    self.mb.labelText = @"正在加载";
    [self.mb hide:YES afterDelay:10];
    [self.mb show:YES];
    
    NSURL *url = [NSURL URLWithString:Urlstr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"网络错误: error: %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.reData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.mb removeFromSuperview];
    
    // 数据加载完成后, 将数据存入本地
    NSString *path = [Path pathOfLibraryWithFileName:self.fileName];
    NSFileManager *file = [NSFileManager defaultManager];
    if ([file fileExistsAtPath:path]) {
        [file removeItemAtPath:path error:nil];
        [self.reData writeToFile:path atomically:YES];
    }
    else {
        [self.reData writeToFile:path atomically:YES];
    }
    
    self.Myblock(self.reData);
}

@end
